<template>
	<view class="container">
		<!-- 广告区域 （前四个暂时不要，ios不能出现）-->
		<!-- <view class="advertisement-field">
			<view class="advertisement-item" @tap="handlerAdClick">
				<text class="iconfont icon-meishi"></text>
				<text class="icon-text">健康美食</text>
			</view>
			<view class="advertisement-item" @tap="handlerAdClick">
				<text class="iconfont icon-qixing"></text>
				<text class="icon-text">健康科普</text>
			</view>
			<view class="advertisement-item" @tap="handlerAdClick">
				<text class="iconfont icon-jiankangyaofang"></text>
				<text class="icon-text">健康药房</text>
			</view>
			<view class="advertisement-item" @tap="handlerAdClick">
				<text class="iconfont icon-AIwenzhen"></text>
				<text class="icon-text">AI问诊</text>
			</view> -->
			<!-- <view class="advertisement-item">
				<text class="iconfont icon-dache"></text>
				<text class="icon-text">打车</text>
			</view>
			<view class="advertisement-item">
				<text class="iconfont icon-dingjiudian"></text>
				<text class="icon-text">订酒店</text>
			</view>
			<view class="advertisement-item">
				<text class="iconfont icon-chongdianzhan"></text>
				<text class="icon-text">充电站</text>
			</view>
			<view class="advertisement-item">
				<text class="iconfont icon-xiaoyouxi"></text>
				<text class="icon-text">小游戏</text>
			</view> -->
		<!-- </view> -->
		<!-- =========================================== -->
		<view class="content">
			<!--头部标签-->
			<view class="head-tag" v-if="showTag">
				<text>订单池</text>
				<uni-icons type="close" @tap="showTag = false" style="margin-left: 20rpx;"></uni-icons>
			</view>
			<!--可接订单列表-->
			<view class="order-list" v-if="driver.getCurrentDriver().auditStatus === auditStatusEnum.PASS.value">
				<!--遍历订单-->
				<view class="order" v-for="order in orderList" :key="order.id">
					<!--订单时间和距离-->
					<view class="order-head">
						<!--时间-->
						<view class="left">
							<text>下单：{{ formatDatetime(order.orderTime) }}</text>
							<text>出发：{{ formatDatetime(order.hopeTime) }}</text>
						</view>
						<!--距离-->
						<view class="right">
							实时
						</view>
					</view>
					<!--订单具体内容-->
					<view class="order-body">
						<view class="distance-from-you">
							<view class="distance">
								<text>距您直线距离：{{ order.distance }}km</text>
							</view>
							<view class="view-more" @tap="gotoInfoPage(order, orderTypeEnum.WAIT.code)">
								<text>查看详情</text>
								<uni-icons type="right" size="14" color="#ccc"></uni-icons>
							</view>
						</view>
						<view class="center">
							<view class="from-and-to">
								<view class="from">
									<view class="dot green"></view>
									<view class="text">{{ order.currentAddr }}</view>
								</view>
								<view class="to">
									<view class="dot red"></view>
									<view class="text">{{ order.targetAddr }}</view>
								</view>
							</view>
							<view class="price">
								<text>预计: </text>
								<text class="num">{{ formatAmount(order.price) }}</text>
								<text>(元)</text>
							</view>
						</view>
						<!--迅速抢单-->
						<view class="btn primary-btn" @tap="handlerGrabOrder(order)">
							迅速抢单
						</view>
					</view>
					
				</view>
				
				<!-- 空状态 -->
				<view class="empty" v-if="orderList.length === 0">
					<image src="/static/imgs/empty.png" mode="aspectFit" alt="暂无订单"></image>
					<text>暂无订单</text>
				</view>
				
				<!--加载更多-->
				<view class="loading-container" v-else>
					<uni-load-more 
						iconType="circle" 
						status="nomore" 
						:content-text="{contentdown: '上拉加载更多', contentrefresh: '正在加载...', contentnomore: '- 到底了 -'}"
					/>
				</view>
			</view>
			<!--待审核-->
			<view class="empty" v-else>
				<image src="/static/imgs/forbid.png" mode="aspectFit" alt="审核通过后可接单"></image>
				<text>提交资料后可接单</text>
				<view class="submit-btn" @tap="gotoEditInfo">前往提交资料</view>
			</view>
		</view>
		<!--开始听单-->
		<view 
			class="listen-btn-container" 
			v-if="driver.getCurrentDriver().auditStatus === auditStatusEnum.PASS.value"
		>
			<view 
				@tap="onChangeListeningState" 
				class="box1 listen-btn" 
				:style="{ backgroundColor: isListening ? 'rgba(220, 44, 25, 0.2)' : 'rgba(43, 153, 255, 0.2)' }"
			>
				<view 
					class="box2 listen-btn" 
					:style="{ backgroundColor: isListening ? 'rgba(220, 44, 25, 0.5)' : 'rgba(43, 153, 255, 0.5)' }"
				>
					<view 
						class="box3 listen-btn" 
						:style="{ backgroundColor: isListening ? 'rgba(220, 44, 25, 0.8)' : 'rgba(43, 153, 255, 0.8)' }"
					>
						{{ isListening ? '结束听单' : '开始听单' }}
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { onMounted, onUnmounted, ref } from 'vue'
import { onPullDownRefresh, onHide, onShow, onReachBottom } from '@dcloudio/uni-app'
import { getOrderList, grabOrder } from '@/api/order.js'
import { formatDatetime } from '@/utils/datetimeUtil.js'
import { useUserStore } from '@/stores/userStore.js'
import { orderTypeEnum } from '@/utils/orderType.js'
import { auditStatusEnum } from '@/utils/enums.js'
import wsClient from '@/ws/ws-client.js'
import { formatAmount } from '@/utils/amountUtil.js'
 

const driver = useUserStore()

const showTag = ref(true)

const orderList = ref([])

let countdown = 0
let timer = null

const latlng = ref({
	latitude: 0,
	longitude: 0
})

const isListening = ref(false)

// 点击广告处理
function handlerAdClick() {
	// 检查是否有登录
	if (!driver.getCurrentDriver().id) {
		showLoginModal()
		return
	}
}

// 前往提交认证资料页面
function gotoEditInfo() {
	// 检查是否有登录
	if(!driver.getCurrentDriver().id){
		showLoginModal()
		return
	}
	uni.navigateTo({
		url: '/pages/mine/edit-info'
	})
}

// 跳转到详情页
function gotoInfoPage (order, status) {
	// 检查是否登录
	if(!driver.getCurrentDriver().id){
		showLoginModal()
		return
	}
	
	order['status'] = status
	// #ifdef APP-PLUS
	uni.navigateTo({
		url: `/pages/index/info?query=${JSON.stringify(order)}`
	})
	// #endif
	// #ifndef APP-PLUS
	uni.navigateTo({
		url: `/pages/index/info2?query=${JSON.stringify(order)}`
	})
	// #endif
}

// 定时器
function startCountdown() {
	countdown = 30
	timer = setInterval(() => {
		if (countdown <= 0) {
			// 清理定时器
			clearInterval(timer)
			// 刷新页面
			init()
			// 继续开启定时
			startCountdown()
			return
		}
		countdown--
		// console.log('定时器工作中: ' + countdown)
	}, 1000)
}

// 查询订单分页
function getOrderPage (longitude, latitude) {
	return new Promise((resolve, reject) => {
		// 发送请求
		getOrderList(longitude, latitude).then(res => {
			orderList.value = res.data
			setTimeout(() => {
				resolve(true)
			}, 500)
		}).catch(e => {
			reject(e)
		})
	})
}

// 抢单
function handlerGrabOrder (order) {
	// 检查是否有登录
	if(!driver.getCurrentDriver().id){
		showLoginModal()
		return
	}
	
	grabOrder(order.id).then(() => {
		uni.showToast({
			icon: 'none',
			title: '抢单成功'
		})
		// 刷新页面
		getOrderPage(latlng.value.longitude, latlng.value.latitude)
		// 跳转页面
		gotoInfoPage(order, orderTypeEnum.GET.code)
	}).catch(err => {
		// 余额不足提示前往充值页面
		const errMsg = err.message || err.response?.data?.message || '抢单失败';
		if(errMsg.includes('账户余额不足')) {
			uni.showModal({
				title:'余额不足',
				content: '您的账户余额不足，请充值后再抢单，是否前往充值页面？',
				confirmText: '前往充值', 
				cancelText: '取消',
				success:(res) => {
					if (res.confirm) {
						uni.navigateTo({
							url:'/pages/mine/recharge'
						})
					}
				}
			})
		}
	})
}

// 获取当前位置 -> 查询订单分页
function init () {
	return new Promise((resolve, reject) => {
		uni.getLocation({
			isHighAccuracy: true, // 高精度
			success: function (res) {
				const { latitude, longitude } = res
				latlng.value.latitude = latitude
				latlng.value.longitude = longitude
				getOrderPage(longitude, latitude).then(() => {
					resolve(true)
				}).catch(e => {
					reject(e)
				})
			},
			fail: function (err) {
				console.log(err)
				reject(err)
			}
		})
	})
}

// 开始听单
function onChangeListeningState () {
	// 检查是否有登录
	if(!driver.getCurrentDriver().id){
		showLoginModal()
		return
	}
	
	isListening.value = !isListening.value
	if (isListening.value) {
		// 建立长连接
		wsClient.initWs({
			la: latlng.value.latitude,
			lo: latlng.value.longitude
		})
	} else {
		// 关闭连接
		wsClient.closeWs()
	}
}

// 未登录弹窗提示
function showLoginModal() {
	uni.showModal({
		title: '提示',
		content: '请先登录后才能进行操作',
		cancelText: '再逛逛',
		confirmText: '去登录',
		success:(res) => {
			if(res.confirm) {
				uni.navigateTo({
					url: '/pages/login-and-register/login'
				})
			}
		}
	})
}
onPullDownRefresh(() => {
	// 如果审核通过
	if (driver.getCurrentDriver().auditStatus === auditStatusEnum.PASS.value) {
		init().then(() => {
			uni.showToast({
				title: '刷新成功',
				icon: 'none'
			})
			uni.stopPullDownRefresh()
		}).catch(e => {
			uni.stopPullDownRefresh()
		})
	} else {
		uni.stopPullDownRefresh()
	}
})

onMounted(() => {
	// 如果审核通过
	if (driver.getCurrentDriver().auditStatus === auditStatusEnum.PASS.value) {
		init()
		startCountdown()
	}
	
	// 监听不允许听单事件
	uni.$on('do-not-connect', () => {
		isListening.value = false
	})
})

</script>

<style lang="scss" scoped>
view {
	box-sizing: border-box;
}
.container {
	width: 100vw;
	min-height: 100vh;
	background-color: #f8f8f8;
	padding: 30rpx;
	/* ================================================= */
	//广告区域
	.advertisement-field {
		margin-top: 30rpx;
		background-color: #ffffff;
		border-radius: 20rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
		padding: 30rpx 10rpx;
		display: flex;
		flex-wrap: wrap;
		justify-content: space-around;
		gap: 10rpx;
		width: 100%;
		.advertisement-item {
			width: 20%;
			height: 160rpx;
			border-radius: 20rpx;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			font-size: 28rpx;
			transition: all 0.2s ease;
			//点击反馈
			&:active {
				transform:scale(0.95);
				background-color: rgba(43, 153, 255, 0.1);
				border-radius: 15rpx;
			}
			.iconfont {
				font-size: 60rpx;
				color: #3f89ff;
				margin-bottom: 10rpx;
			}
			.icon-text {
				font-size: 26rpx;
				color: #333333;
				white-space: nowrap; // 禁止文字换行
			}
		}
	}
/* ======================================= */
	.content {
		width: 100%;
		height: 100%;
		// 顶部提示
		.head-tag {
			margin-top: 30rpx;
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: center;
			padding-bottom: 30rpx;
			font-size: 26rpx;
			color: #666;
		}
		// 订单列表
		.order-list {
			padding-bottom: 300rpx;
			// 订单
			.order {
				background-color: #fff;
				border-radius: 20rpx;
				margin-bottom: 20rpx;
				box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
				.order-head {
					display: flex;
					align-items: center;
					justify-content: space-between;
					padding: 20rpx;
					border-bottom: 1rpx solid #ddd;
					font-size: 26rpx;
					.left {
						display: flex;
						align-items: center;
						text {
							margin-right: 25rpx;
						}
					}
					.right {
						font-size: 24rpx;
						color: #fff;
						padding: 10rpx;
						border-radius: 15rpx;
						background-color: #2979ff;
					}
				}
				.order-body {
					padding: 20rpx;
					.distance-from-you {
						margin-bottom: 20rpx;
						display: flex;
						align-items: center;
						justify-content: space-between;
						.distance {
							font-size: 28rpx;
							font-weight: 600;
						}
						.view-more {
							font-size: 24rpx;
							color: #666;
							display: flex;
							align-items: center;
						}
					}
					.center {
						display: flex;
						align-items: center;
						justify-content: space-between;
						.from-and-to {
							&>view {
								margin-bottom: 20rpx;
								font-size: 28rpx;
								display: flex;
								align-items: center;
								justify-content: flex-start;
								.dot {
									width: 18rpx;
									height: 18rpx;
									border-radius: 50%;
									margin-right: 15rpx;
								}
								.green {
									background-color: #00b400;
								}
								.red {
									background-color: #d60000;
								}
								.text {
									white-space: nowrap;
									overflow: hidden;
									text-overflow: ellipsis;
									width: 300rpx;
								}
							}
							.from {
							}
							.to {
							}
						}
						.price {
							font-size: 26rpx;
							display: flex;
							align-items: center;
							justify-content: center;
							.num {
								font-size: 34rpx;
								font-weight: 600;
								color: #e00;
							}
						}
					}
					.btn {
						width: 100%;
						text-align: center;
						padding: 30rpx 0;
						border-radius: 15rpx;
					}
				}
			}
		
			// 加载更多
			.loading-container {
				text-align: center;
				// padding: 20rpx;
				font-size: 22rpx;
			}
		}
	}
	
	// 开始听单
	.listen-btn-container {
		position: fixed;
		// #ifdef APP-PLUS
		bottom: 0;
		// #endif
		// #ifndef APP-PLUS
		bottom: 100rpx;
		// #endif
		left: 0;
		width: 100%;
		height: 300rpx;
		// background-color: red;
		
		display: flex;
		justify-content: center;
		align-items: center;
		color: white;
		font-size: 32rpx;
		
		.box1 {
			width: 250rpx;
			height: 250rpx;
			box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.1);
			.box2 {
				width: 200rpx;
				height: 200rpx;
				.box3 {
					width: 150rpx;
					height: 150rpx;
				}
			}
		}
		
		.listen-btn {
			border-radius: 50%;
			
			display: flex;
			align-items: center;
			justify-content: center;
			
			transition: all 0.2s ease;
			&:active {
				transform: scale(0.95);
				opacity: 0.9;
			}
		}
		
	}
}

// 空 或 禁用
.empty {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	height: 70vh;

	image {
		width: 500rpx;
		height: 500rpx;
		margin-bottom: 30rpx;
		opacity: 0.6;
	}

	text {
		color: #666;
		font-size: 28rpx;
	}
	.submit-btn {
		margin-top: 30rpx;
		background-color: #2b99ff;
		color: white;
		padding: 20rpx 60rpx;
		border-radius: 40rpx;
		font-size: 28rpx;
		transition: all 0.2s ease;
		&:active {
			transform: scale(0.95);
			opacity: 0.9;
		}
	}
}
</style>